/*
 * @Author: wei_jt@ecidi.com
 * @Date: 2020-11-18 19:16:07
 * @LastEditors: wei_jt@ecidi.com
 * @LastEditTime: 2022-04-18 19:49:01
 * @Description: file content
 */
import storage from '../storage'
import store from '@/store'
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import { GET_LANG } from '@/store/Action/actionTypes'

const loadedLanguages = [] //已加载语言

function setI18nLanguage (lang) {
  Vue.config.lang = lang
  storage.set('lang_config', lang)
  store.commit('SET_CURRENT_LANG', lang)
  Vue.prototype.$lang = lang //默认系统配置语言

  return lang
}

export function loadLanguageAsync (lang) {
  store.dispatch(GET_LANG, lang)
  if (!loadedLanguages.includes(lang)) {
    return import(/* webpackChunkName: "lang-[request]" */ `fawkes-lib/lib/locale/lang/${lang}`).then(msgs => {
      Vue.locale(lang, msgs.default)
      loadedLanguages.push(lang)
      return setI18nLanguage(lang)
    })
  }
  return Promise.resolve(setI18nLanguage(lang))
}


/**
 * @description: 获取本地语言设置 当未配置时，选择浏览器默认语言
 * @param {type} 
 * @return: 
 */
export function getLangConfig () {
  let language = storage.get('lang_config') || store.getters.language
  if (language) return language
  if (navigator.appName == 'Netscape') {
    language = navigator.language || navigator.userLanguage
  }
  else {
    language = navigator.browserLanguage || navigator.userLanguage
  }
  if (language.indexOf('en') > -1) {
    language = 'en'
  }
  else if (language.indexOf('zh') > -1) {
    language = 'zh-CN'
  }
  else {
    language = 'en'
  }
  return language
}

function loadModules () {
  const modules = require.context('/src', true, /lang.js$/, 'lazy')
  sessionStorage.setItem('locale', JSON.stringify(modules.keys()))
}


const locale = {}
locale.install = function (Vue) {
  //国际化
  const lang = getLangConfig()
  Vue.prototype.$lang = store.getters.language || lang //默认系统配置语言

  Vue.use(VueI18n)
  loadLanguageAsync(lang)
  if (!sessionStorage.getItem('locale')) {
    loadModules()
  }
}

export default locale
